<template>
  <edit-dialog
    :centerDialogVisible="visible"
    :tilte="tilte"
    :default-button="false"
    @Cancel="handleCancel"
    :width="width"
  >
    <template #content>
      <div style="height: 450px;overflow-y: auto;overflow-x: hidden;">
        <el-form
          ref="addGoodsFormRef"
          :model="addForm"
          :rules="rules"
          label-position="right"
          label-width="125px"
          :inline="true"
        >
          <el-form-item label="物品名称：" prop="goodsName">
            <el-input
              v-model.trim="addForm.goodsName"
              placeholder="请输入物品名称"
              maxlength="20"
              clearable
            />
          </el-form-item>
          <el-form-item label="物品类型：" prop="goodsType">
            <el-select
              v-model="addForm.goodsType"
              placeholder="请选择"
              @change="handlerGoodsTypeChange"
            >
              <el-option
                v-for="item in goodsType"
                :label="item.goodsType"
                :value="item.typeId"
                :key="item.typeId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="保质期：" prop="timeLimit">
            <el-input v-model="addForm.timeLimit" maxlength="20">
              <template #append>
                <el-select v-model="addForm.timeLimitUnit" placeholder="请选择">
                  <el-option label="小时" value="H" />
                  <el-option label="天" value="D" />
                  <el-option label="年" value="Y" />
                </el-select>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="失主姓名：" prop="lostName">
            <el-input
              v-model.trim="addForm.lostName"
              placeholder="请输入失主姓名"
              maxlength="20"
            />
          </el-form-item>
          <el-form-item label="失主电话：" prop="lostPhone">
            <el-input
              maxlength="15"
              v-model.trim="addForm.lostPhone"
              placeholder="请输入失主电话"
            />
          </el-form-item>
          <br />
          <el-form-item label="遗失时间：" class="lost-time" prop="lostTime">
            <el-date-picker
              v-model="addForm.lostTime"
              type="datetimerange"
              format="YYYY-MM-DD HH:mm:ss"
              range-separator="至"
            />
          </el-form-item>
          <br />
          <el-form-item label="航站楼：" prop="lostTerminal">
            <el-select v-model.trim="addForm.lostTerminal" placeholder="请选择">
              <el-option
                v-for="item in terminal"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="具体遗失地点：" prop="lostPlace">
            <el-input
              maxlength="20"
              v-model.trim="addForm.lostPlace"
              placeholder="请输入具体遗失地点"
            />
          </el-form-item>
          <br />
          <el-form-item label="图片：" class="upload-img">
            <el-upload
              ref="uploadRef"
              v-model:file-list="fileList"
              :action="baseUrlConfig.businessBaseUrl+'/fast/uploadFile'"
              list-type="picture-card"
              :on-success="handlerUploadSuccess"
              :on-error="handlerUploadError"
              :before-upload="handlerBeforeUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              limit="10"
              :on-exceed="handleExceed"
              :class="{ hide: hideUpload }"
            >
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
            <el-dialog align-center v-model="dialogVisible" width="auto" center>
              <div>
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
              </div>
            </el-dialog>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button class="buttonCancel" @click="handleCancel">取消</el-button>
        <el-button
          class="btn-ok"
          @click="handleAddSubmit(addGoodsFormRef)"
          :loading="loading"
          >确定</el-button
        >
        <el-button
          class="btn-match"
          @click="handleMatch(addGoodsFormRef)"
          v-if="isAdd"
          :loading="matchLoading"
          >立即匹配</el-button
        >
      </span>
    </template>
  </edit-dialog>
  <!-- 匹配 -->
  <Match
    :visible="matchDialogVisible"
    :state="2"
    :info="goodsObject"
    @cancel="cancel"
    @showAdd="showAdd"
    @submit="submit"
  />
</template>

<script lang="ts" setup>
import { ref, reactive, defineProps, computed, watch } from "vue";
import { useStore } from "vuex";
import type {
  FormInstance,
  FormRules,
  UploadProps,
  UploadUserFile,
} from "element-plus";
import editDialog from "@/components/editDialog/index.vue";
import { ElMessage } from "element-plus";
import { deleteFile } from "@/api/common";
import {baseUrlConfig} from '@/config/config'
import Match from "./match.vue";
import {
  lostGoodsAppend,
  lostGoodsEdit,
  LostGoodsAppendItem,
} from "@/api/lose/goodsLost";
import dayjs from "dayjs";
const matchDialogVisible = ref(false);
interface RuleForm {
  lostId: string;
  goodsName: string;
  goodsType: string;
  lostName: string;
  lostPhone: string;
  lostTime: Array<string>;
  lostTimeStart: string;
  lostTimeEnd: string;
  timeLimit: number;
  timeLimitUnit: string;
  goodsLimitTime: string;
  lostTerminal: string;
  lostPlace: string;
  files: Array<{
    enclosureContent: string;
    enclosureName: string;
    enclosureSuffix: string;
    resourceAddress: string;
    enclosureCode: string;
  }>;
  creator: {
    id: string;
    name: string;
    organId: string;
    organName: string;
  };
}
const addGoodsFormRef = ref<FormInstance>();
const uploadRef = ref();
const hideUpload = ref(false);
const loading = ref(false);
const matchLoading = ref(false);
const tilte = ref("遗失物品预约登记");
const width = ref("775px");
const store = useStore();
const disabled = ref(false);
const userInfo = computed(() => store.state.user.userInfo);
const terminal = computed(() => store.state.terminal.data);
const goodsObject = ref({});
const initForm = reactive<RuleForm>({
  lostId: "",
  goodsName: "",
  lostTime: [],
  goodsType: "",
  lostName: "",
  lostPhone: "",
  lostTimeStart: "",
  lostTimeEnd: "",
  timeLimit: 1,
  timeLimitUnit: "",
  goodsLimitTime: "",
  lostTerminal: "",
  lostPlace: "",
  files: [],
  creator: {
    id: "",
    name: "",
    organId: "",
    organName: "",
  },
});
const addForm = reactive({})

interface FileFace {
  enclosureContent: string;
  enclosureName: string;
  enclosureSuffix: string;
  resourceAddress: string;
  enclosureCode: string;
}
const goodsFile = ref<Array<FileFace>>([]);
const validatePhone = (rule: any, value: any, callback: any) => {
  if (!value) return callback(new Error("请输入手机号"));
  if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(value))
    return callback(new Error("手机号格式错误"));
  callback();
};
const rules = reactive<FormRules>({
  goodsName: [
    { required: true, message: "请输入物品类型名称", trigger: "blur" },
    { max: 50, message: "最大长度50", trigger: "blur" },
  ],
  lostPhone: [
    { required: true, message: "请输入捡拾手机号", trigger: "blur" },
    { required: true, validator: validatePhone, trigger: "blur" },
  ],
  lostTerminal: [
    { required: true, message: "请选择遗失航站楼", trigger: "blur" },
  ],
  goodsType: [{ required: true, message: "请选择物品类型", trigger: "blur" }],
  timeLimit: [{ required: true, message: "请输入保质期", trigger: "blur" }],
  timeLimitUnit: [
    { required: true, message: "请选择保质期单位", trigger: "blur" },
  ],
  lostTime: [{ required: true, message: "请遗失时间", trigger: "blur" }],
  lostName: [{ required: true, message: "请输入失主姓名", trigger: "blur" }],
});

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  goodsType: {
    type: Array,
  },
  info: {
    type: Object,
  },
  isAdd: {
    type: Boolean,
    default: true,
  },
  state: {
    // 判断是否需要精空表单，默认是
    type: Boolean,
    default: true,
  },
});

const fileList = ref<UploadUserFile[]>([]);

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const emit = defineEmits(["cancel", "submit", "showAdd"]);
const handleExceed: UploadProps["onExceed"] = (uploadFile, uploadFiles) => {
  ElMessage.error("上传文件数不能超过10个");
};
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  let code = "";
  if (uploadFile.response) {
    code = uploadFile.response.data?.enclosureCode;
  } else {
    code = uploadFile.name;
  }
  delFile(code);
  hideUpload.value = false;
  const values: Array<FileFace> = [];
  goodsFile.value.forEach((item, index) => {
    if (item.enclosureCode !== code) {
      values.push(item);
    }
  });
  goodsFile.value = values;
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

// 上传前
const handlerBeforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log(rawFile)
  const fileSuffix = rawFile.name.substring(rawFile.name.lastIndexOf('.') + 1)
  const whiteList = ['jpg', 'png', 'JPG', 'PNG']
  if (whiteList.indexOf(fileSuffix) === -1) {
    ElMessage.error('上传文件类型只能是 jpg,png,JPG,PNG格式')
    return false
  }
  if (rawFile.size > 10 * 1024 * 1024) {
    ElMessage.error('文件大小只能在10M以内')
    return false
  }
}

// 上传成功
const handlerUploadSuccess: UploadProps["onSuccess"] = (
  resp,
  uploadFile,
  uploadFiles
) => {
  console.log(resp, uploadFile, uploadFiles);
  if (resp.code === "1") {
    const item: FileFace = {
      enclosureContent: resp.data.enclosureCode,
      enclosureName: resp.data.enclosureName,
      enclosureSuffix: resp.data.enclosureSuffix,
      resourceAddress: resp.data.resourceAddress,
      enclosureCode: resp.data.enclosureCode,
    };
    goodsFile.value.push(item);
    if (goodsFile.value.length >= 10) {
      hideUpload.value = true;
    }
  }
};

const handlerUploadError: UploadProps["onError"] = (
  error,
  uploadFile,
  uploadFiles
) => {
  console.log(error, uploadFile, uploadFiles);
};

const delFile = (code: string) => {
  deleteFile(code).then((res) => {
    console.log(res);
  });
};

/**
 * 物品类型改变事件
 */
const handlerGoodsTypeChange = (row: any) => {
  const data = {};
  for (const item of props.goodsType) {
    if (item.typeId === row) {
      data = item;
      break;
    }
  }
  disabled.value = true;
  // if (data.goodsType !== "一般物品") {
    addForm.timeLimit = data.timeLimit;
    addForm.timeLimitUnit = data.timeLimitUnit;
    disabled.value = false;
  // }
};

const cancel = () => {
  matchDialogVisible.value = false;
  emit("cancel");
};

const showAdd = (val) => {
  matchDialogVisible.value = false;
  emit("showAdd", val);
};
const submit = () => {
  matchDialogVisible.value = false;
};

/**
 * 取消
 */
const handleCancel = async () => {
  emit("cancel");
};

/**
 * 匹配
 */
const handleMatch = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    return;
  }
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      matchLoading.value = true;
      const payload: LostGoodsAppendItem = { ...addForm };
      if (addForm.lostTime) {
        payload.lostTimeStart = addForm.lostTime[0];
        payload.lostTimeEnd = addForm.lostTime[1];
        payload.lostTimeStart = payload.lostTimeStart
          ? dayjs(payload.lostTimeStart).format("YYYY-MM-DD HH:mm:ss")
          : "";
        payload.lostTimeEnd = payload.lostTimeEnd
          ? dayjs(payload.lostTimeEnd).format("YYYY-MM-DD HH:mm:ss")
          : "";
        // 计算时效
        if (addForm.lostTime) {
          let unit: any = "hour";
          if (addForm.timeLimitUnit === "Y") {
            unit = "year";
          } else if (addForm.timeLimitUnit === "D") {
            unit = "day";
          }
          // 计算间隔天数
          const intervalDay = dayjs(payload.lostTimeEnd).diff(
            payload.lostTimeStart,
            "day"
          );
          // 计算中间值
          const middle = intervalDay / 2;
          addForm.goodsLimitTime = dayjs(payload.lostTimeStart)
            .add(middle, "day")
            .add(addForm.timeLimit, unit)
            .format("YYYY-MM-DD HH:mm:ss");
        }
        payload.goodsLimitTime = addForm.goodsLimitTime;
      }
      payload.files = goodsFile.value ? goodsFile.value : [];
      let fetch = lostGoodsAppend;
      if (addForm.lostId) {
        // 编辑
        fetch = lostGoodsEdit;
        payload.lostId = addForm.lostId;
        payload.lastMember = {
          id: userInfo.value.userId,
          name: userInfo.value.name,
          organId: userInfo.value.organId,
          organName: userInfo.value.organName,
        };
      } else {
        payload.creator = {
          id: userInfo.value.userId,
          name: userInfo.value.name,
          organId: userInfo.value.organId,
          organName: userInfo.value.organName,
        };
        delete payload.lostId;
      }
      await fetch(payload)
        .then((res) => {
          if (res?.code === "1") {
            matchDialogVisible.value = true;
            matchLoading.value = false;
            if (res.data?.lostId) {
              addForm.lostId = res.data.lostId;
              goodsObject.value = {
                lostId: res.data.lostId,
                goodsName: addForm.goodsName,
                goodsType: addForm.goodsType,
                lostTimeStart: payload.lostTimeStart,
                lostTimeEnd: payload.lostTimeEnd,
              };
            }
            emit("submit");
          } else {
            ElMessage.error(res?.message || "操作失败，请重试！");
          }
          console.log("Submit!");
        })
        .catch((err) => {
          ElMessage.error(err.message || "操作失败，请重试！");
          matchDialogVisible.value = false;
        });
    }
  });
};

/**
 * 提交
 */
const handleAddSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    return;
  }
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      const payload: LostGoodsAppendItem = { ...addForm };
      if (addForm.lostTime) {
        payload.lostTimeStart = addForm.lostTime[0];
        payload.lostTimeEnd = addForm.lostTime[1];
        payload.lostTimeStart = payload.lostTimeStart
          ? dayjs(payload.lostTimeStart).format("YYYY-MM-DD HH:mm:ss")
          : "";
        payload.lostTimeEnd = payload.lostTimeEnd
          ? dayjs(payload.lostTimeEnd).format("YYYY-MM-DD HH:mm:ss")
          : "";
        delete payload.lostTime;
        // 计算时效
        if (addForm.lostTime) {
          let unit: any = "hour";
          if (addForm.timeLimitUnit === "Y") {
            unit = "year";
          } else if (addForm.timeLimitUnit === "D") {
            unit = "day";
          }
          // 计算间隔天数
          const intervalDay = dayjs(payload.lostTimeEnd).diff(
            payload.lostTimeStart,
            "day"
          );
          // 计算中间值
          const middle = intervalDay / 2;
          addForm.goodsLimitTime = dayjs(payload.lostTimeStart)
            .add(middle, "day")
            .add(addForm.timeLimit, unit)
            .format("YYYY-MM-DD HH:mm:ss");
        }
        payload.goodsLimitTime = addForm.goodsLimitTime;
      }
      payload.files = goodsFile.value;
      let tips = "新增";
      let fetch = lostGoodsAppend;
      if (addForm.lostId) {
        // 编辑
        fetch = lostGoodsEdit;
        tips = "编辑";
        payload.lostId = addForm.lostId;
        payload.lastMender = {
          id: userInfo.value.userId,
          name: userInfo.value.name,
          organId: userInfo.value.organId,
          organName: userInfo.value.organName,
        };
      } else {
        payload.creator = {
          id: userInfo.value.userId,
          name: userInfo.value.name,
          organId: userInfo.value.organId,
          organName: userInfo.value.organName,
        };
      }
      await fetch(payload)
        .then((res) => {
          if (res?.code === "1") {
            addGoodsFormRef.value?.resetFields();
            uploadRef.value?.clearFiles();
            hideUpload.value = false;
            ElMessage.success(tips + "成功！");
            emit("submit");
          } else {
            ElMessage.error(res?.message || tips + "失败，请重试！");
          }
          console.log("Submit!");
        })
        .catch((err) => {
          ElMessage.error(err.message || tips + "失败，请重试！");
          loading.value = false;
        });
    } else {
      console.log("error submit!", fields);
    }
    loading.value = false;
  });
};
watch(
  () => props.visible,
  async (val) => {
    if (!props.state) {
      Object.assign(addForm,initForm)
      addGoodsFormRef.value?.resetFields();
      await uploadRef.value?.clearFiles();
    }
    if (val && props.state) {
      console.log("props.info", props.info)
      addForm.timeLimit = 1;
      addForm.lostId = "";
      hideUpload.value = false;
      goodsFile.value = [];
      if (props.info?.lostId) {
        const info = props.info;
        addForm.goodsName = info.goodsName;
        addForm.goodsType = info.goodsType;
        addForm.timeLimit = info.timeLimit;
        addForm.timeLimitUnit = info.timeLimitUnit;
        addForm.lostName = info.lostName;
        addForm.lostPhone = info.lostPhone;
        addForm.lostPlace = info.lostPlace;
        addForm.lostTerminal = info.lostTerminal;
        addForm.lostId = info.lostId;
        addForm.lostTime = [];
        if (info.lostTimeStart) {
          addForm.lostTime.push(info.lostTimeStart);
        }
        if (info.lostTimeEnd) {
          addForm.lostTime.push(info.lostTimeEnd);
        }
        if (info.files) {
          addForm.files = info.files;
          goodsFile.value = info.files;
          fileList.value = [];
          info.files.forEach((ele) => {
            fileList.value.push({
              name: ele.enclosureCode,
              url: ele.resourceAddress,
            });
          });
        }
      }
    }
  }
);
</script>

<style lang="less" scoped>
.hide {
  /deep/ .el-upload--picture-card {
    display: none;
  }
  /deep/ .el-list-enter-active,
  .el-list-leave-active {
    transition: all 0s;
  }
  /deep/ .el-list-enter,
  .el-list-leave-active {
    opacity: 0;
    transform: translateY(0);
  }
}
.upload-img {
  width: 100%;
}
/deep/.el-form-item__content {
  width: 200px;
}
.lost-time {
  /deep/.el-form-item__content {
    width: 350px;
  }
}
.buttonCancel {
  width: 80px;
  background: #fff;
}
.buttonCancel:hover {
  color: green;
  border-color: green;
  background: #fff;
}
.btn-ok {
  width: 80px;
  color: #337fcc;
  border: 1px solid #337fcc;
}
.btn-match {
  width: 80px;
  color: #fff;
  background: #337fcc;
  border-radius: 6px;
  border: 1px solid #337fcc;
}
</style>
